/*
 * Title: WADS
 * Description: Web-based Auto flow Documents System
 * Copyright: 2007
 * Company: CoE
 * @author: Mr.Nattasan Wang-Aphisit
 * @version 1.1
 */

package wads.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import wads.com.AutoDocumentTransaction;
import wads.com.DocumentTemplateInfo;
import wads.com.UserInfo;
import wads.com.WADTools;

public class ManageUnSuccessDocumentServlet extends HttpServlet {
  private static final long serialVersionUID = 715858684597467433L;
  
  private static final String CONTENT_TYPE = WADTools.SERVLET_CONTENT_TYPE;
  /**Initialize global variables*/
  private String app_Path;
  private Vector documentIDFile;
  private AutoDocumentTransaction adTran;
  private DocumentTemplateInfo dtInfo;
  private String template_ID;
  //private String template_Name;
  private String ownerName;
  //private String sendDate;
  //private String updateDate;
  private ServletOutputStream sos;
  private UserInfo uiRestrictUser;
  private String fullNameRestrict;
  private UserInfo uiPowerUser;
  private String fullNamePower;
  //private String powerName;
  private String createdTime;
  private String submitTime;
  private Vector nameofUsertoShow = new Vector();
  //public final int LIMITUP_GREEN  = 5;
  //public final int LIMITDOWN_YELLOW = 6;
  //public final int LIMITUP_YELLOW = 10;
  //public final int LIMITDOWN_RED    = 11;
  int LIMITUP_GREEN;
  int LIMITDOWN_YELLOW;
  int LIMITUP_YELLOW;
  int LIMITDOWN_RED;
  Properties prop = new Properties();
  String color;
  int percent;
  String image;
  String emailPowerUser;
  Calendar cal_ct, cal_st;

  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }
  /**Process the HTTP Get request*/
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    //app_Path = this.getInitParameter("app_Path");
    app_Path = WADTools.APP_PATH;
    sos = response.getOutputStream();
    prop.load(new FileInputStream(app_Path+"res/day.properties"));
    LIMITUP_GREEN    = Integer.parseInt(prop.getProperty("LIMITUP_GREEN"));
    LIMITDOWN_YELLOW = Integer.parseInt(prop.getProperty("LIMITDOWN_YELLOW"));
    LIMITUP_YELLOW   = Integer.parseInt(prop.getProperty("LIMITUP_YELLOW"));
    LIMITDOWN_RED    = Integer.parseInt(prop.getProperty("LIMITDOWN_RED"));

    //add
    this.readBeginninghtml();
    //choose user to show
    nameofUsertoShow = this.findAllPowerUser();
    //before call function. must be add allUser that to show
    this.fillDataAll(nameofUsertoShow);

    sos.close();

  }
  /**Clean up resources*/
  public void destroy() {
  }

  public Vector findAllPowerUser(){
    Vector<String> allPowerUser = new Vector<String>();
    File doc_Path = new File(app_Path+"res/docs/InProgressAutoDoc/");
    if(doc_Path.isDirectory()){
      File[] listUserPath = doc_Path.listFiles();
      for(int i=0; i<listUserPath.length ;i++)
        allPowerUser.add(listUserPath[i].getName());
    }

    return allPowerUser;
  }

  public Vector getDocumentInUser(String user){
    Vector<String> documentIDFile = new Vector<String>();
    File user_Path = new File(app_Path+"res/docs/InProgressAutoDoc/" + user);
    File[] listDocument = user_Path.listFiles();
    for(int i=0; i< listDocument.length; i++)
      documentIDFile.add(listDocument[i].getName());

    return documentIDFile;
  }

  public void readBeginninghtml() {
    File htmlFile = new File("inProcessDocument.html");
    String temp = null;
    byte[] buf = new byte[1024];
    boolean check = true;
    try{
      BufferedReader br = new BufferedReader(new FileReader(htmlFile));
      while((temp = br.readLine()) != null){
        if((temp.indexOf("hiddenField") == -1) && check){
          // sos.println(temp);
          buf = temp.getBytes();
          sos.write(buf,0,temp.length());
        }else{
          check = false;
        }
        //this.fillDataAll();
      }
      br.close();
    }catch(Exception e){
      System.out.println("Exception thrown from ManageUnSuccessDocumentServlet.readBegininghtml()");
      e.printStackTrace();
    }
  }

  public void fillDataAll(Vector usertoShow){
    //  String user = "power1";
    String user = null;
    String BGColor;
    int h=0;

    for(int j=0; j<usertoShow.size(); j++){
      user = usertoShow.elementAt(j).toString();
      documentIDFile = this.getDocumentInUser(user);
      for(int i=0; i<documentIDFile.size(); i++){

        if(h%2 != 0)
          BGColor = "#F0F0F0";
        else
          BGColor = "#CCCCCC";
        
        h++;
        try{
          ObjectInputStream ois = new ObjectInputStream(new FileInputStream(app_Path+"res/docs/InProgressAutoDoc/"+user+"/"+documentIDFile.elementAt(i)));
          adTran = (AutoDocumentTransaction)ois.readObject();
          template_ID = adTran.getTemplate_ID();
          //template_Name = adTran.getTemplate_Name();

          //get ownerName FullName of User
          ownerName = this.getFullNameofRestrictedUser(adTran.getOwner_Name());
          //get powerUserName FullName of PowerUser
          //powerName = this.getFullNameofPowerUser(user);
          //powerName = "<a href=mailto:" + emailPowerUser + ">" + powerName + "</a>";

          //get createdTime
          createdTime = this.getCreatedTime(adTran.getCreated_Date());
          //get submitTime after
          submitTime = this.getSubmitTime(Calendar.getInstance().getTime());
          /*if(adTran.getSubmitDate() != null)
            submitTime = this.getSubmitTime(adTran.getSubmitDate().getTime());
          else
            submitTime = createdTime;*/

          //get percent to manage document
          percent = this.getProgressBarPercent(user);
          //get color to show time of document
          if(adTran.getSubmitDate() != null)
            color = this.getProgressBarColor(adTran.getCreated_Date(),Calendar.getInstance().getTime());
          else{
            Date stDate = adTran.getCreated_Date();
            color = this.getProgressBarColor(adTran.getCreated_Date(),stDate);
          }
          ///combine String image to show
          image = "../images/" + color + "_" + percent + ".gif";

          String delete = "<a href=servlet/delete?ID=" + adTran.getTransaction_ID() + "&user=" +
            user + ">" + "<img src=../images/bin.gif width=\"20\" height=\"20\">" + "</a>";


          //String to call servlet to flow document instead currentuser
          //String flow = "<a href=servlet/manageFlow"

          //sendDate = adTran.getCreated_Date().toString();
          //updateDate = adTran.getCurrentTime().toString();


          ObjectInputStream oisa = new ObjectInputStream(
            new FileInputStream(app_Path+"res/docs/activeDocTemplate/" + template_ID + "/docTemplate.info"));
          dtInfo = (DocumentTemplateInfo)oisa.readObject();
          String ID = dtInfo.getTemplate_Name();

          ID = "<a href=servlet/show?ID=" + adTran.getTransaction_ID() + "&user=" + user + ">" + ID + "</a>";

          //add adminflow servlet
          String flow = "<a href=servlet/adminflow?ID=" + adTran.getTransaction_ID() + "&user=" +
            user + ">" + "Accept" + "</a>";

          String temp = " <tr bgcolor="+ BGColor +"><td width=60>" + template_ID +
            "</td><td width=200>" + ID +
            "</td><td width=200>" + ownerName +
            "</td><td width=50>" + createdTime +
            "</td><td width=200>" + "<a href=mailto:" + emailPowerUser + ">" + fullNamePower + "</a>" +
            "</td><td width=50>" + submitTime +
            "</td><td width=20>" + flow +
            "</td><td width=200><img src="+ "\"" + image + "\"" + "width=200 height=12>" +
            "</td><td width=30>" + delete + "</td></tr>";

          sos.write(temp.getBytes(),0,temp.length());
          ois.close();
        }catch(Exception e) {
          System.out.println("Exception thrown from ManageUnSuccessDocumentServlet.fillDataAll()");
          e.printStackTrace();
        }

     }
    }
  }

  public String getFullNameofRestrictedUser(String name){
    String restrictUserFile = app_Path+"res/user/RestrictUser/RestrictUser.org";

    //Read Object of RestrictUser
    try{
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream(restrictUserFile));
      uiRestrictUser = (UserInfo)ois.readObject();
      ois.close();
    }catch(Exception e) {
      System.out.println("Exception thrown from ManageUnSuccessDocumentServlet.getFullNameofRestrictedUser()");
      e.printStackTrace();
    }

    if(!uiRestrictUser.isEmpty()){
       for(int i=0; i<uiRestrictUser.getSize(); i++){
          if(name.equals(uiRestrictUser.getUserDataAt(i).getUsername()))
            fullNameRestrict = uiRestrictUser.getUserDataAt(i).getName();
       }
    }

    return fullNameRestrict;
  }

  public String getFullNameofPowerUser(String name){
    String powerUserFile= null;
    String orgName = null;
    Properties prop = new Properties();

    try{
      //Load OrgName of PowerUser
      prop.load(new FileInputStream(app_Path+"res/wad_app.properties"));
      orgName = prop.getProperty("orgName","No");
      powerUserFile = app_Path+"res/user/PowerUser/" + orgName;

      //Read Object of RestrictUser
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream(powerUserFile));
      uiPowerUser = (UserInfo)ois.readObject();
      ois.close();
    }catch(Exception e){System.out.println(e);}

    if(!uiPowerUser.isEmpty()){
       for(int i=0; i<uiPowerUser.getSize(); i++){
          if(name.equals(uiPowerUser.getUserDataAt(i).getUsername())){
            fullNamePower = uiPowerUser.getUserDataAt(i).getName();
            emailPowerUser = uiPowerUser.getUserDataAt(i).getEMail();
          }
       }
    }
    return fullNamePower;
  }

  public String getCreatedTime(Date createdTime){
    cal_ct.setTime(createdTime);
    int date = cal_ct.get(Calendar.DAY_OF_MONTH);
    int month = cal_ct.get(Calendar.MONTH);
    int year = cal_ct.get(Calendar.YEAR)-57;

    return date + "/" + month + "/" + year;
  }

  public String getSubmitTime(Date submitTime){
    cal_st.setTime(submitTime);
    int date = cal_st.get(Calendar.DAY_OF_MONTH);
    int month = cal_st.get(Calendar.MONTH);
    int year = cal_st.get(Calendar.YEAR)-57;

    return date + "/" + month + "/" + year;
  }

  public String getProgressBarColor(Date createdTime, Date submitTime){
    String color = null;
    cal_ct.setTime(createdTime);
    cal_st.setTime(submitTime);
    int ctDate  = cal_ct.get(Calendar.DAY_OF_MONTH);
    int ctMonth = cal_ct.get(Calendar.MONTH);
    int ctYear  = cal_ct.get(Calendar.YEAR)-57;
    int stDate  = cal_st.get(Calendar.DAY_OF_MONTH);
    int stMonth = cal_st.get(Calendar.MONTH);
    int stYear  = cal_st.get(Calendar.YEAR)-57;
    int check = 0;
    int def = 0;
    if(createdTime.equals(submitTime)){
      return "green";
    }else{
      if((def = (stYear - ctYear)) > 0)
        check = check + (def * 365);

      if((def = (stMonth - ctMonth)) > 0)
        check = check + (def * 30);

      if((def = (stDate - ctDate)) > 0)
        check = check + def;
      ///check limit
    }
    
    if(check >= 0 && check <= LIMITUP_GREEN)
      color = "green";
    else if(check >= LIMITDOWN_YELLOW && check <= LIMITUP_YELLOW)
      color = "yellow";
    else if(check >= LIMITDOWN_RED)
      color = "red";

    return color;
  }
  
  public int getProgressBarPercent(String currentUser){
    int numberUser = 0;
    int indexCurrentUser = 0;
    int percent = 0;
    String user = null;
    String temp = "0";

    try{
      ObjectInputStream oisa = new ObjectInputStream(new FileInputStream(app_Path+"res/docs/activeDocTemplate/"+template_ID+"/docTemplate.info"));
      dtInfo = (DocumentTemplateInfo)oisa.readObject();
      oisa.close();
    }catch(Exception e) {
      System.out.println("Exception thrown from ManageUnSuccessDocumentServlet.getProgressBarPercent()");
      e.printStackTrace();
    }
    
    if(!dtInfo.getFlow_Users().isEmpty()){
      int i=1;

      user = dtInfo.getFirstUser();
      if(currentUser.equals(user))
        indexCurrentUser = i-1;

      while((user = dtInfo.whois_nextUser_from_thisUser(user)) != null){
        i++;
        if(currentUser.equals(user))
          indexCurrentUser = i-1;
        numberUser = i;
      }
    }
    if((indexCurrentUser != 0) && (numberUser != 0)){
      percent = (int)((indexCurrentUser*100)/numberUser);
      temp = String.valueOf(percent);
      temp = temp.substring(0,temp.length()-1);
      temp = temp + "0";
    }
    return Integer.parseInt(temp);
  }
}
